package com.jimmy.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jimmy.reggie.common.CustomException;
import com.jimmy.reggie.entity.Category;
import com.jimmy.reggie.entity.Dish;
import com.jimmy.reggie.entity.Setmeal;
import com.jimmy.reggie.mapper.CategoryMapper;
import com.jimmy.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishServiceImpl dishService;
    @Autowired
    private SetmealServiceImpl setmealService;

    /**
     * 这里因为表结构的逻辑关联，需要进行删除的拓展操作
     * 查询当前的分类是否已经关联了菜品和套餐信息，如果关联了直接抛出异常，禁止用户进行删除操作
     * @param id
     */
    @Override
    public void deleteByid(Long id) {
        /*
          重复逻辑：
          Dish和Setmeal是重复性逻辑，根据菜品的id来查询对应的表中是否存在数据关联，有就抛出异常
         */
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        int count = dishService.count(dishLambdaQueryWrapper);
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int count1 = setmealService.count(setmealLambdaQueryWrapper);
        if (count>0||count1>0){
            throw  new CustomException("当前分类关联了菜品或者套餐，无法删除");
        }
        super.removeById(id);
    }
}
